package com.example.cxz2021606127.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.cxz2021606127.R;
import com.example.cxz2021606127.util.ExitActivityUtil;
import com.example.cxz2021606127.util.MySqLiteHelper;
import com.example.cxz2021606127.util.ToastUtil;
import com.google.android.material.textfield.TextInputEditText;

public class LoginActivity extends AppCompatActivity {
    private MySqLiteHelper helper;
    private String name, psw;
    private TextInputEditText edtMainName;
    private TextInputEditText edtMainPsw;
    private Button btnMainLogin;
    private Button btnMainRegister;
    SQLiteDatabase database;

    //第一次点击退出发生的时间
    private long firstExitTime;

    //点击两次返回键退出app   System.currentTimeMillis()表示系统当前时间
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - firstExitTime > 2000)) {   //系统当前时间减去第一次点击退出时间大于2秒
                Toast toast = Toast.makeText(getApplicationContext(), "再按一次退出最新闻", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);  //改变Toast的位置
                toast.show();
                firstExitTime = System.currentTimeMillis();
            } else {
                ExitActivityUtil.getInstance().exitAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        //添加该Activity到ExitActivityUtil对象实例容器中
        ExitActivityUtil.getInstance().addActivity(this);

        //数据库操作
        helper = new MySqLiteHelper(this, "SAVE_USER.db", null, 1);
        database = helper.getReadableDatabase();


        //登录按钮点击事件
        //验证当前账号、密码是否跟注册在数据库的账号、密码一致，一致则允许登录
        btnMainLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取输入框文本
                String username = edtMainName.getText().toString().trim();
                String mpassword = edtMainPsw.getText().toString().trim();
                if (username.equals("") || mpassword.equals("")) {
                    ToastUtil.showMsg(LoginActivity.this, "请输入账号/密码");
                } else {
                    Cursor cursor = database.query("user", null, null, null, null, null, null);
                    if (cursor.moveToFirst()) {
                        do {
                            //从数据库获取到用户名、密码
                            name = cursor.getString(cursor.getColumnIndex("name"));
                            psw = cursor.getString(cursor.getColumnIndex("password"));
                            if (username.equals(name) && mpassword.equals(psw)) {
                                //提示
                                Toast.makeText(LoginActivity.this, "登陆成功！", Toast.LENGTH_LONG).show();
                                //账号密码校验正确
                                // 登陆成功，跳转的用户界面
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                            } else if (username.equals(name) && !mpassword.equals(psw)) {
                                edtMainPsw.setError("密码错误");
                            } else if (mpassword.equals(psw) && !username.equals(name)) {
                                edtMainName.setError("账号错误");
                            }

                        } while (cursor.moveToNext());
                    }
                    //关闭游标
                    cursor.close();


                }
            }
        });

        //注册按钮点击事件
        btnMainRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });
    }

    private void initView() {
        edtMainName = (TextInputEditText) findViewById(R.id.edt_main_name);
        edtMainPsw = (TextInputEditText) findViewById(R.id.edt_main_psw);
        btnMainLogin = (Button) findViewById(R.id.btn_main_login);
        btnMainRegister = (Button) findViewById(R.id.btn_main_register);
    }

    /**
     * 自定义注册页面对话框
     */
    public void register() {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        View view = LayoutInflater.from(LoginActivity.this).inflate(R.layout.activity_register, null, false);
        builder.setView(view);
        Dialog dialog = builder.create();

        //注册界面控件初始化
        TextInputEditText edtMainName = (TextInputEditText) view.findViewById(R.id.edt_main_name);
        TextInputEditText edtMainPsw = (TextInputEditText) view.findViewById(R.id.edt_main_psw);
        TextInputEditText edtMainPsw2 = (TextInputEditText) view.findViewById(R.id.edt_main_psw2);
        Button btnMainRegister = (Button) view.findViewById(R.id.btn_main_register);
        Button btnMainCancel = (Button) view.findViewById(R.id.btn_main_cancel);

        //注册按钮点击事件
        btnMainRegister.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String RegisterUser = edtMainName.getText().toString().trim();
                String RegisterPassword = edtMainPsw.getText().toString().trim();
                String RegisterPassword2 = edtMainPsw2.getText().toString().trim();
                Cursor cursor = database.query("user", null, null, null, null, null, null);
                if (cursor.moveToFirst()) {
                    do {
                        //从数据库获取到用户名
                        name = cursor.getString(cursor.getColumnIndex("name"));
                    } while (cursor.moveToNext());
                }
                //关闭游标
                cursor.close();
                //判断输入的账号密码是否为空，是则提示用户输入正确的
                if (RegisterUser.equals("") || RegisterPassword.equals("") || RegisterPassword2.equals("")) {
                    ToastUtil.showMsg(LoginActivity.this, "请输入账号/密码");
                } else if (!RegisterPassword.equals(RegisterPassword2)) {
                    edtMainPsw2.setError("两次输入的密码不一致");
                } else
                    if (name.equals(RegisterUser)) {
                    edtMainName.setError("该账号已存在");
                } else
                    {
                    database = helper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    //键值对的形式
                    values.put("name", RegisterUser);
                    values.put("password", RegisterPassword);
                    //添加到user表
                    database.insert("user", null, values);
                    Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                }

            }
        });

        //取消按钮点击事件
        btnMainCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();


    }

}